<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\command;

use app\enum\KuaishouLeyuanEnum;
use app\service\autobuild\kuaishou\LeyuanService;
use think\console\Input;
use think\console\Output;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Exception;

class KsAutoBuildLeyuanWork extends BaseWork
{
    protected function configure()
    {
        $this->setName('ks_auto_build_leyuan');
        $this->setDescription('快手自动批量搭建-客户233');
    }

    protected function execute(Input $input, Output $output)
    {
        set_time_limit(0);
        ini_set('memory_limit', '-1');
        $output->writeln('快手自动批量搭建-客户233搭建开始==========' . date('Y-m-d H:i:s') . '==========');
        $start = time();
        foreach (KuaishouLeyuanEnum::AUTO_BUILD_CONFIG as $configType => $infos) {
            foreach ($infos as $config) {
                if (empty($config['advertiser_id'])) {
                    continue;
                }

                // 账户
                $advertiserIds = $config['advertiser_id'];
                foreach ($advertiserIds as $advertiserId) {
                    $leyuanService = new LeyuanService();
                    $output->writeln('广告主账户ID：' . $advertiserId . '搭建开始==========' . date('Y-m-d H:i:s'));
                    $advStart = time();
                    try {
                        if (! $leyuanService->autoBuild($advertiserId, $configType, $config)) {
                            throw new Exception(LeyuanService::getError(0));
                        }
                    } catch (DataNotFoundException $dne) {
                        $output->writeln('广告主账户ID：' . $advertiserId . '异常==========DataNotFoundException：' . $dne->getMessage());
                    } catch (ModelNotFoundException $me) {
                        $output->writeln('广告主账户ID：' . $advertiserId . '异常==========ModelNotFoundException' . $me->getMessage());
                    } catch (DbException $de) {
                        $output->writeln('广告主账户ID：' . $advertiserId . '异常==========DbException' . $de->getMessage());
                    } catch (\Exception $e) {
                        $output->writeln('广告主账户ID：' . $advertiserId . '异常==========Exception' . $e->getMessage());
                    } finally {
                        $output->writeln('广告主账户ID：' . $advertiserId . '搭建结束==========' . date('Y-m-d H:i:s') . '，用时：' . round((time() - $advStart) / 60, 2) . '分钟');
                    }
                }
            }
        }
        $output->writeln('快手自动批量搭建-客户233搭建结束==========' . date('Y-m-d H:i:s') . '==========，总用时：' . round((time() - $start) / 60, 2) . '分钟');
    }
}
